﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace OrderManager.Broadcast
{
    class MessageCenter
    {
        private static readonly MessageCenter instance = new MessageCenter();

        public static MessageCenter Instance { get { return instance; } }

        private Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        private EndPoint remoteIP = null;
        private EndPoint broadcaseIP = new IPEndPoint(IPAddress.Broadcast, 3666);

        private byte[] reciveBuf = new byte[1024 * 1024];

        private byte[] sendBuf = new byte[1024 * 1024];

        private BinaryFormatter binaryFormatter = new BinaryFormatter();

        public event EventHandler<MessageArrviedEventArgs> MessageArrived;

        public MessageCenter()
        {
            this.udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
        }

        private void DataReviceCallback(IAsyncResult ar)
        {
            try
            {
                int ret = this.udpSocket.EndReceiveFrom(ar, ref this.remoteIP);
                if (ret <= 0)
                {
                    return;
                }
                MemoryStream ms = new MemoryStream(this.reciveBuf, 0, ret);
                Message m = this.binaryFormatter.Deserialize(ms) as Message;
                if (this.MessageArrived != null)
                {
                    this.MessageArrived(this, new MessageArrviedEventArgs(m));
                }
            }
            catch
            {
                this.udpSocket.Close();
            }
        }

        public void Start()
        {
            this.udpSocket.BeginReceiveFrom(this.reciveBuf, 0, this.reciveBuf.Length, SocketFlags.None, ref this.remoteIP, this.DataReviceCallback, null);
        }

        public void Close()
        {
            this.udpSocket.Close();
        }

        public void SendMessage(Message message)
        {
            MemoryStream ms = new MemoryStream(this.sendBuf);
            this.binaryFormatter.Serialize(ms, message);
            var buf = ms.ToArray();
            this.udpSocket.SendTo(buf, this.broadcaseIP);
        }
    }
}
